
from os import listdir
import numpy as np
from sklearn.svm import SVC


def loadDataSet():
    # 导入训练集
    trainFileList = listdir('data/HWdigits/trainSet')
    trainNum = len(trainFileList)

    trainX = np.zeros((trainNum, 32*32))
    trainY = []

    for i in range(trainNum):
        trainFile = trainFileList[i]
        trainX[i,:] = img2vector('data/HWdigits/trainSet/%s' % trainFile, 32, 32)
        label = int(trainFile.split('_')[0])  #读文件
        trainY.append(label)

    #导入测试集
    testFileList = listdir('data/HWdigits/testSet')
    testNum = len(testFileList)
    testX = np.zeros((testNum, 32*32))
    testY = []
    for i in range(testNum):
        testFile = testFileList[i]
        testX[i,:] = img2vector('data/HWdigits/testSet/%s' % testFile, 32, 32)
        label = int(testFile.split('_')[0])
        testY.append(label)

    return trainX, trainY, testX, testY


def img2vector(filename, h, w):
    imgVector = np.zeros((1, h*w))
    fileIn = open(filename)
    for row in range(h):
        lineStr = fileIn.readline()
        for col in range(w):
            imgVector[0, row*32+col] =int(lineStr[col])
    return imgVector

#def myKNN():

def mySVM(testDigit):
    #predict = model.predict([test_x[i]])
    predict = model.predict([testDigit])

    return predict

if __name__ == '__main__':
    train_x,train_y,test_x,test_y = loadDataSet()
    numTestSamples = test_x.shape[0]
    matchCount=0
    #model = SVC(kernel= 'linear', C=1).fit(train_x,train_y)
    model = SVC(kernel='linear', C=1)
    model.fit(train_x,train_y)
    #print('3.Find the most frequent label in ??')
    #print('4.Show the result...')
    for i in range(0, numTestSamples):
        #predict = model.predict(test_x[[i]])
        predict = model.predict([test_x[i]])
        #predict = mySVM(test_x[i])
        #print('result is: %d, real answer is: %d' % (predict,test_y[i]))
        if predict == test_y[i]:
            matchCount += 1
    accuracy = float(matchCount)/numTestSamples
    print('The total number of error is: %d' % (numTestSamples-matchCount))
    print("The classify accuracy is: : %.2f%%" % (accuracy*100))
    print(model.score(test_x,test_y))

